#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from database import con
import time





# 创建任务历史表
def job_createTable():
    cur = con.cursor()
    sql = '''
    CREATE TABLE IF NOT EXISTS "job_history" -- 任务执行历史
     (
	    "id"	INTEGER UNIQUE,
        "state"	INTEGER, -- 状态 0 默认 1运行中  2完成退出 3异常退出
	    "name"	TEXT NOT NULL,  -- 任务名称
	    "pid"	TEXT NOT NULL, -- 任务pid
        "changeTime"    TEXT,
        "creatTime"    TEXT,
	    PRIMARY KEY("id" AUTOINCREMENT)
        )
    '''
    cur.execute(sql)
    con.commit()

# 添加一个历史任务
def job_add(pid,name,state):
    cur = con.cursor()
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = ('''
    INSERT INTO job_history 
    (name,pid,state,creatTime) 
    VALUES 
    ('%s', '%s', '%s', '%s')
    ''' % (name, pid, state, now))
    cur.execute(sql)
    con.commit()
    return cur.lastrowid

# 更新任务状态
def job_update(pid,state):
    cur = con.cursor()
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = ('''
    UPDATE  job_history 
    SET 
    state='%s' ,
    changeTime='%s'
    where pid='%s'
    ''' % (state,now,pid))
    cur.execute(sql)
    con.commit()



job_createTable()